package org.usmile.algorithms.learn.sort;

import java.util.Arrays;
import java.util.Random;

/**
 * 三路快排
 */
public class ThreeWayQuickSorter {
    public void sort(int[] nums) {
        if (nums == null || nums.length <= 1) {
            return;
        }
        int left = 0;
        int right = nums.length - 1;

        sort(nums, left, right);
    }

    private void sort(int[] nums, int left, int right) {
        if (left >= right) {
            return;
        }

        int[] partition = partition(nums, left, right);
        sort(nums, left, partition[0] - 1);
        sort(nums, partition[1] + 1, right);
    }

    private int[] partition(int[] nums, int left, int right) {
        int randomIndex = new Random().nextInt(right - left + 1) + left;
        int pivot = nums[randomIndex];

        int i = left;
        int less = left;
        int great = right;
        while (i <= great) {
            if (nums[i] > pivot) {
                swap(nums, i, great);

                great--;
            } else if (nums[i] < pivot) {
                swap(nums, i, less);
                less++;
                i++;
            } else {
                i++;
            }
        }

        return new int[]{less, great};
    }

    private void swap(int[] nums, int i, int j) {
        int temp = nums[j];
        nums[j] = nums[i];
        nums[i] = temp;
    }

    public static void main(String[] args) {
        int[] nums = new int[]{1, 4, 9, 9, 5, 20, 18, 9, 7, 10, 9};
        new ThreeWayQuickSorter().sort(nums);

        System.out.println(Arrays.toString(nums));
    }
}